package dao

import (
	"errors"
	"time"
	"user_srv/basic/config"
	"user_srv/handler/model"
)

var (
	ErrCannotAddSelf  = errors.New("不能添加自己为好友")
	ErrAlreadyFriend  = errors.New("已经是好友")
	ErrGroupNotFound  = errors.New("分组不存在")
	ErrFriendNotFound = errors.New("好友不存在")
)

type FriendService struct{}

// AddFriend 建立双向好友关系（各插入一条），并归入分组
func (s *FriendService) AddFriend(userId, targetUserId, groupId int64, remark string) error {
	if userId <= 0 || targetUserId <= 0 || userId == targetUserId {
		return ErrCannotAddSelf
	}

	// 确保分组存在或使用默认分组
	var groupModel model.XqFriendGroups
	g, err := groupModel.EnsureDefault(userId)
	if err != nil {
		return err
	}
	if groupId == 0 {
		groupId = g.Id
	}
	// 校验指定分组归属
	if groupId != g.Id {
		var check model.XqFriendGroups
		if err := config.DB.Where("id = ? AND user_id = ?", groupId, userId).First(&check).Error; err != nil {
			return ErrGroupNotFound
		}
	}

	// 已经是好友?
	var uf model.XqUserFriends
	ok, err := uf.IsFriend(userId, targetUserId)
	if err != nil {
		return err
	}
	if ok {
		return ErrAlreadyFriend
	}

	now := time.Now()
	// 单向记录A->B
	recA := &model.XqUserFriends{UserId: userId, FriendId: targetUserId, GroupId: groupId, Remark: remark, IsActive: 1, CreatedAt: now}
	if err := recA.Create(); err != nil {
		return err
	}
	// 单向记录B->A（对方默认分组）
	g2, err := groupModel.EnsureDefault(targetUserId)
	if err != nil {
		return err
	}
	recB := &model.XqUserFriends{UserId: targetUserId, FriendId: userId, GroupId: g2.Id, Remark: "", IsActive: 1, CreatedAt: now}
	if err := recB.Create(); err != nil {
		return err
	}
	return nil
}

// RemoveFriend 移除双向好友（软删除）
func (s *FriendService) RemoveFriend(userId, targetUserId int64) error {
	var uf model.XqUserFriends
	if err := uf.Update(model.XqUserFriends{UserId: userId, FriendId: targetUserId}); err != nil {
		return err
	}
	// 实际更新需要设置is_active=0
	if err := config.DB.Model(&model.XqUserFriends{}).
		Where("user_id = ? AND friend_id = ?", userId, targetUserId).
		Updates(map[string]interface{}{"is_active": 0}).Error; err != nil {
		return err
	}

	if err := config.DB.Model(&model.XqUserFriends{}).
		Where("user_id = ? AND friend_id = ?", targetUserId, userId).
		Updates(map[string]interface{}{"is_active": 0}).Error; err != nil {
		return err
	}
	return nil
}

// MoveFriendToGroup 变更分组
func (s *FriendService) MoveFriendToGroup(userId, targetUserId, toGroupId int64) error {
	var check model.XqFriendGroups
	if err := config.DB.Where("id = ? AND user_id = ?", toGroupId, userId).First(&check).Error; err != nil {
		return ErrGroupNotFound
	}
	return config.DB.Model(&model.XqUserFriends{}).
		Where("user_id = ? AND friend_id = ? AND is_active = 1", userId, targetUserId).
		Updates(map[string]interface{}{"group_id": toGroupId}).Error
}

// CreateGroup 新建分组
func (s *FriendService) CreateGroup(userId int64, name string) (int64, error) {
	g := &model.XqFriendGroups{UserId: userId, GroupName: name}
	if err := g.Create(); err != nil {
		return 0, err
	}
	return g.Id, nil
}

// RenameGroup 重命名
func (s *FriendService) RenameGroup(userId, groupId int64, name string) error {
	return config.DB.Model(&model.XqFriendGroups{}).
		Where("id = ? AND user_id = ? AND is_default = 0", groupId, userId).
		Updates(map[string]interface{}{"group_name": name}).Error
}

// DeleteGroup 删除分组，将好友迁移到默认分组
func (s *FriendService) DeleteGroup(userId, groupId int64) error {
	var group model.XqFriendGroups
	if err := config.DB.Where("id = ? AND user_id = ?", groupId, userId).First(&group).Error; err != nil {
		return ErrGroupNotFound
	}
	if group.IsDefault == 1 {
		return errors.New("默认分组不可删除")
	}
	def, err := group.EnsureDefault(userId)
	if err != nil {
		return err
	}
	if err := config.DB.Model(&model.XqUserFriends{}).
		Where("user_id = ? AND group_id = ? AND is_active = 1", userId, groupId).
		Updates(map[string]interface{}{"group_id": def.Id}).Error; err != nil {
		return err
	}
	return (&model.XqFriendGroups{Id: groupId}).Delete(model.XqFriendGroups{Id: groupId})
}
